<template>
  <div class="page-container">
    <el-card v-loading="loading" class="main-card">
      <template #header>
        <div class="card-header">
          <div>
            <h3>{{ customNodeType?.name || '自定义节点类型' }}</h3>
            <el-tag v-if="customNodeType?.currentVersion" size="small" type="success">
              当前版本: v{{ customNodeType.currentVersion }}
            </el-tag>
            <el-tag v-else size="small" type="info">未发布</el-tag>
          </div>
          <div class="header-actions">
            <el-button @click="goBack">返回列表</el-button>
            <el-button type="success" @click="viewVersions">版本管理</el-button>
            <el-button type="primary" @click="saveAsNewVersion" :loading="submitting">
              保存为新版本
            </el-button>
          </div>
        </div>
      </template>
      
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="ID">{{ customNodeType?.id }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ customNodeType?.createTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="customNodeType?.published ? 'success' : 'info'">
            {{ customNodeType?.published ? '已发布' : '未发布' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ customNodeType?.description }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="node-code-section">
        <div class="section-header">
          <h4>自定义节点代码</h4>
          <div>
            <el-button type="primary" size="small" @click="testCode">测试</el-button>
            <el-dropdown @command="handleCodeTemplate" split-button type="primary" size="small">
              加载模板
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="stringProcessingExample">字符串处理模板</el-dropdown-item>
                  <el-dropdown-item command="mathCalculationExample">数学计算模板</el-dropdown-item>
                  <el-dropdown-item command="asyncOperationExample">异步操作模板</el-dropdown-item>
                  <el-dropdown-item command="arrayProcessingExample">数组处理模板</el-dropdown-item>
                  <el-dropdown-item command="jsonProcessingExample">JSON处理模板</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="code-editor-container">
          <el-input
            v-model="nodeCode"
            type="textarea"
            resize="none"
            :rows="20"
            placeholder="在此编写自定义节点代码，可以使用异步操作"
            class="code-editor"
          />
        </div>
        
        <div class="docs-section">
          <h4>说明文档</h4>
          <div class="docs-form">
            <el-form label-position="top">
              <el-form-item label="参数说明">
                <el-input 
                  v-model="parametersDocs" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="描述此节点类型接收哪些参数"
                />
              </el-form-item>
              <el-form-item label="返回值说明">
                <el-input 
                  v-model="returnDocs" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="描述此节点类型返回什么结果"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 新版本创建弹窗 -->
    <el-dialog
      v-model="versionDialogVisible"
      title="创建新版本"
      width="500px"
    >
      <el-form :model="versionForm" label-width="120px" ref="versionFormRef" :rules="versionRules">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="versionForm.version" placeholder="例如: 1.0.0" />
        </el-form-item>
        <el-form-item label="版本说明" prop="description">
          <el-input 
            v-model="versionForm.description" 
            type="textarea" 
            placeholder="描述此版本的变更内容"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="立即发布">
          <el-switch v-model="versionForm.publish" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createVersion" :loading="submitting">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 测试运行弹窗 -->
    <el-dialog
      v-model="testDialogVisible"
      title="测试自定义节点"
      width="600px"
    >
      <div class="test-container">
        <h4>测试参数</h4>
        <el-form label-position="top">
          <el-form-item label="参数 (JSON格式)">
            <el-input 
              v-model="testParams" 
              type="textarea" 
              :rows="5" 
              placeholder='{"param1": "value1", "param2": 123}'
            />
          </el-form-item>
        </el-form>
        
        <el-button type="primary" @click="runTest" :loading="testRunning">
          运行测试
        </el-button>
        
        <div v-if="testResult" class="test-results">
          <h4>测试结果</h4>
          <div class="result-box">
            <pre>{{ JSON.stringify(testResult, null, 2) }}</pre>
          </div>
        </div>
        
        <div v-if="testError" class="test-error">
          <h4>错误信息</h4>
          <div class="error-box">
            <pre>{{ testError }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customNodeExamples } from '../examples/customNodeExamples'

const store = useStore()
const router = useRouter()
const route = useRoute()

const loading = ref(false)
const submitting = ref(false)
const versionDialogVisible = ref(false)
const testDialogVisible = ref(false)
const testRunning = ref(false)
const versionFormRef = ref(null)

// 节点代码及文档
const nodeCode = ref('')
const parametersDocs = ref('')
const returnDocs = ref('')

// 测试相关数据
const testParams = ref('{\n  "example": "test"\n}')
const testResult = ref(null)
const testError = ref(null)

// 版本表单
const versionForm = ref({
  version: '',
  description: '',
  publish: false
})

const versionRules = {
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { 
      pattern: /^\d+\.\d+\.\d+$/, 
      message: '版本号格式应为: 主版本.次版本.修订版本，例如: 1.0.0', 
      trigger: 'blur' 
    }
  ],
  description: [
    { required: true, message: '请输入版本说明', trigger: 'blur' }
  ]
}

const customNodeType = computed(() => store.state.currentCustomNodeType)

// 监听自定义节点类型变化，更新表单数据
watch(customNodeType, (newValue) => {
  if (newValue) {
    // 检查是否有基于现有版本创建的数据
    const baseVersionStr = localStorage.getItem('baseVersion')
    if (baseVersionStr) {
      try {
        const baseVersion = JSON.parse(baseVersionStr)
        
        // 确保基于的版本属于当前节点类型
        if (baseVersion.nodeTypeId === newValue.id) {
          nodeCode.value = baseVersion.code || ''
          parametersDocs.value = baseVersion.parametersDocs || ''
          returnDocs.value = baseVersion.returnDocs || ''
          
          // 显示提示消息
          ElMessage.info({
            message: `已加载版本 v${baseVersion.version} 的数据作为基础，您可以在此基础上修改并创建新版本`,
            duration: 5000
          })
          
          // 清除localStorage中的数据，避免下次进入页面时重复加载
          localStorage.removeItem('baseVersion')
          return
        }
      } catch (error) {
        console.error('解析基础版本数据失败:', error)
        localStorage.removeItem('baseVersion')
      }
    }
    
    // 如果没有基于现有版本的数据，或解析失败，则加载当前节点类型数据
    nodeCode.value = newValue.code || ''
    parametersDocs.value = newValue.parametersDocs || ''
    returnDocs.value = newValue.returnDocs || ''
  }
})

// 获取自定义节点类型详情
const fetchNodeTypeDetail = async () => {
  loading.value = true
  try {
    await store.dispatch('fetchCustomNodeTypeById', route.params.id)
  } catch (error) {
    ElMessage.error('获取自定义节点类型详情失败')
  } finally {
    loading.value = false
  }
}

// 返回列表页
const goBack = () => {
  router.push('/custom-nodes')
}

// 查看版本历史
const viewVersions = () => {
  router.push(`/custom-nodes/${route.params.id}/versions`)
}

// 保存为新版本
const saveAsNewVersion = () => {
  // 验证代码是否为空
  if (!nodeCode.value || nodeCode.value.trim() === '') {
    ElMessage.warning('节点代码不能为空')
    return
  }
  
  // 检查是否基于现有版本
  const baseVersionStr = localStorage.getItem('baseVersion')
  let baseVersion = null
  if (baseVersionStr) {
    try {
      baseVersion = JSON.parse(baseVersionStr)
    } catch (error) {
      console.error('解析基础版本数据失败:', error)
    }
  }
  
  // 使用当前日期生成版本建议
  const now = new Date()
  let suggestedVersion = `${now.getFullYear() - 2023}.${now.getMonth() + 1}.${now.getDate()}`
  
  // 如果基于现有版本，建议在原版本基础上递增
  if (baseVersion) {
    // 尝试解析版本号
    try {
      const versionParts = baseVersion.version.split('.').map(Number)
      // 增加补丁版本号
      versionParts[2] += 1
      suggestedVersion = versionParts.join('.')
    } catch (error) {
      console.error('版本号递增失败:', error)
    }
  }
  
  // 初始化表单数据
  versionForm.value = {
    version: suggestedVersion,
    description: baseVersion ? `基于 v${baseVersion.version} 版本的改进` : '',
    publish: false
  }
  
  versionDialogVisible.value = true
}

// 创建新版本
const createVersion = async () => {
  if (!versionFormRef.value) return
  
  await versionFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 更新自定义节点类型的基本信息和代码
        await store.dispatch('updateCustomNodeType', {
          id: customNodeType.value.id,
          nodeType: {
            ...customNodeType.value,
            code: nodeCode.value,
            parametersDocs: parametersDocs.value,
            returnDocs: returnDocs.value
          }
        })
        
        // 创建新版本
        const version = {
          id: `version_${Date.now()}`,
          nodeTypeId: customNodeType.value.id,
          version: versionForm.value.version,
          description: versionForm.value.description,
          code: nodeCode.value,
          parametersDocs: parametersDocs.value,
          returnDocs: returnDocs.value,
          createTime: new Date().toLocaleDateString()
        }
        
        await store.dispatch('createCustomNodeVersion', {
          nodeTypeId: customNodeType.value.id,
          version
        })
        
        // 如果选择了立即发布，则发布此版本
        if (versionForm.value.publish) {
          await store.dispatch('publishCustomNodeVersion', {
            nodeTypeId: customNodeType.value.id,
            versionId: version.id
          })
        }
        
        ElMessage.success('版本创建成功')
        versionDialogVisible.value = false
        
        // 重新获取节点类型信息
        await fetchNodeTypeDetail()
      } catch (error) {
        ElMessage.error('创建版本失败: ' + error.message)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 处理代码模板选择
const handleCodeTemplate = (command) => {
  if (!customNodeExamples[command]) {
    ElMessage.warning('模板不存在')
    return
  }
  
  ElMessageBox.confirm(
    '加载模板将覆盖当前代码，是否继续？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    nodeCode.value = customNodeExamples[command]
    ElMessage.success('模板加载成功')
  }).catch(() => {
    // 用户取消操作
  })
}

// 测试代码
const testCode = () => {
  if (!nodeCode.value || nodeCode.value.trim() === '') {
    ElMessage.warning('节点代码不能为空')
    return
  }
  
  testDialogVisible.value = true
  testResult.value = null
  testError.value = null
}

// 运行测试
const runTest = async () => {
  testRunning.value = true
  testResult.value = null
  testError.value = null
  
  try {
    // 解析测试参数
    let params = {}
    try {
      params = JSON.parse(testParams.value)
    } catch (error) {
      testError.value = `参数JSON解析错误: ${error.message}`
      return
    }
    
    // 创建可执行的函数代码
    let functionCode = nodeCode.value.trim()
    
    // 如果代码不是函数形式，则进行包装
    if (!functionCode.startsWith('function') && !functionCode.includes('=>')) {
      functionCode = `function(params) { ${functionCode} }`
    }
    
    // 执行代码
    // eslint-disable-next-line no-new-func
    const customFunction = new Function('return ' + functionCode)()
    
    // 执行函数，支持异步
    const result = await Promise.resolve(customFunction(params))
    
    // 显示结果
    testResult.value = result
  } catch (error) {
    testError.value = error.message
  } finally {
    testRunning.value = false
  }
}

// 清除本地存储的基础版本数据（用于处理异常情况）
onUnmounted(() => {
  localStorage.removeItem('baseVersion')
})

onMounted(() => {
  fetchNodeTypeDetail()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.node-code-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.code-editor-container {
  margin-bottom: 20px;
}

.code-editor {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
}

.docs-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.test-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.test-results,
.test-error {
  margin-top: 20px;
}

.result-box {
  background-color: #f8f9fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.error-box {
  background-color: #fef0f0;
  border: 1px solid #fab6b6;
  border-radius: 4px;
  padding: 10px;
  color: #f56c6c;
}
</style> 